package storage

import (
	"context"
	"net/http"
	"net/url"
	"os"

	"github.com/tencentyun/cos-go-sdk-v5"
)

func CosPut(sourcePath string, fileName string) (string, error) {
	// 将 examplebucket-1250000000 和 COS_REGION 修改为真实的信息
	u, _ := url.Parse("https://gocos-1252347112.cos.ap-guangzhou.myqcloud.com")
	b := &cos.BaseURL{BucketURL: u}
	c := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  "AKIDLUN0N16aVAYgY9LXLtABw5ze5HEvwhhQ",
			SecretKey: "bw1FF0Wnpb8QTIsDJAm9HAoDNIyPbYFg",
		},
	})
	// 对象键（Key）是对象在存储桶中的唯一标识。
	// 例如，在对象的访问域名 `examplebucket-1250000000.cos.COS_REGION.myqcloud.com/test/objectPut.go` 中，对象键为 test/objectPut.go
	name := "file/" + fileName
	// 3.通过文件流上传对象
	fd, err := os.Open(sourcePath)
	if err != nil {
		return "", err
	}
	defer fd.Close()
	_, errPut := c.Object.Put(context.Background(), name, fd, nil)
	if errPut != nil {
		return "", errPut
	}
	return "https://gocos-1252347112.cos.ap-guangzhou.myqcloud.com/file/" + fileName, nil
}
